package com.sunshine.homepage.service.impl;

import com.sunshine.homepage.doamin.Repertory;
import com.sunshine.homepage.doamin.commodity;
import com.sunshine.homepage.mapper.CommodityAndRepertoryMapper;
import com.sunshine.homepage.mapper.RepertoryMapper;
import com.sunshine.homepage.mapper.commodityMapper;
import com.sunshine.homepage.service.HomepageMerchantService;
import com.sunshine.util.minio.MinIOService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional  // 启用事务管理
public class  HomepageMerchantServiceImpl implements HomepageMerchantService {
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private CommodityAndRepertoryMapper commodityAndRepertoryMapper;
    @Autowired
    private commodityMapper commodityMapper;
    @Autowired
    private RepertoryMapper repertoryMapper;

    /**
     * 添加商品
     *
     * @param commodityName      商品名称
     * @param productDescription 商品描述
     * @param commodityBrand     商品品牌
     * @param commodityCategory  商品分类
     * @param commodityPicture   商品图片
     * @param price              商品价格
     * @return
     */
    @Override
    public Map<String, Object> addCommodity(String commodityName, String productDescription, Integer repertoryNumber, String commodityBrand, String commodityCategory, MultipartFile commodityPicture, Double price) {
        // 检查必要参数
        if (commodityName == null || commodityName.isEmpty() || price == null || commodityCategory == null || commodityCategory.isEmpty()) {
            throw new IllegalArgumentException("商品名称、价格和分类不能为空");
        }
        
        Date date = new Date();
        Map<String, Object> params = new HashMap<>();

        // 创建商品对象
        commodity record = new commodity();
        record.setName(commodityName);
        record.setProductDescription(productDescription);
        record.setCommodityBrand(commodityBrand);
        record.setCommodityCategory(commodityCategory);
        record.setCreateTime(date);
        record.setUpdateTime(date);
        record.setPrice(price);

        // 将商品对象放入参数中
        params.put("record", record);

        if (commodityPicture != null && !commodityPicture.isEmpty()) {
            try {
                // 确保存储桶存在
                minIOService.createBucketIfNotExists();
                String s = minIOService.uploadFile(commodityPicture);
                record.setCommodityPicture(s);
            } catch (Exception e) {
                throw new RuntimeException("添加图片失败: " + e.getMessage());
            }
        }

        params.put("repertoryNumber", repertoryNumber);

        // 执行插入操作，此时record.id将包含生成的ID
        commodityAndRepertoryMapper.insertCommodityWithOptionalRepertory(params);
        
        // 如果提供了库存数量，则插入库存记录
        if (repertoryNumber != null) {
            Map<String, Object> repertoryParams = new HashMap<>();
            repertoryParams.put("commodityId", record.getId());
            repertoryParams.put("repertoryNumber", repertoryNumber);
            commodityAndRepertoryMapper.insertRepertory(repertoryParams);
        }

        // 将生成的ID添加到返回结果中
        params.put("id", record.getId());
        return params;
    }

    /**
     * 修改商品
     *
     * @param id                 商品ID
     * @param commodityName      商品名称
     * @param productDescription 商品描述
     * @param commodityBrand     商品品牌
     * @param commodityCategory  商品分类
     * @param commodityPicture   商品图片
     * @param price              商品价格
     * @return
     */
   @Override
    public Map<String, Object> updateCommodity(Integer id, String commodityName, String productDescription, Integer repertoryNumbe,String commodityBrand, String commodityCategory, MultipartFile commodityPicture, Double price) {
        Map<String, Object> map = new HashMap<>();
        commodity commodity = new commodity();
        Repertory repertory = new Repertory();

            Date date = new Date();
            commodity.setId(id);
            commodity.setName(commodityName);
            commodity.setProductDescription(productDescription);
            commodity.setCommodityBrand(commodityBrand);
            commodity.setCommodityCategory(commodityCategory);
            commodity.setUpdateTime(date);

            // 只有在提供了商品图片时才执行上传逻辑
            if (commodityPicture != null && !commodityPicture.isEmpty()) {
                try {
                    // 确保存储桶存在
                    minIOService.createBucketIfNotExists();
                    String s = minIOService.uploadFile(commodityPicture);
                    commodity.setCommodityPicture(s);
                } catch (Exception e) {
                    throw new RuntimeException("添加图片失败: " + e.getMessage());
                }
            }

            commodity.setPrice(price);
            repertory.setNumber(repertoryNumbe);
            map.put("commodity", commodity);
            map.put("repertory", repertory);
            int updateCount = commodityAndRepertoryMapper.updateCommodityAndRepertory(map);
            
            // 检查是否有记录被更新
            if (updateCount == 0) {
                throw new RuntimeException("未找到ID为 " + id + " 的商品，更新失败");
            }
            
            map.put("updateCount", updateCount);
            return map;
    }

    /**
     * 删除商品
     * @param id 商品ID
     * @return
     */
    @Override
    public boolean deleteCommodity(Integer id) {

        commodityMapper.deleteByPrimaryKey(id);

        return true;
    }
}
